package com.atguigu.srb.sms.controller.api;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.utlis.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin
@Slf4j
public class ApiSmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号",required = true)
            @PathVariable String mobile
    ){
       //调用service_core服务的验证手机号接口，验证手机号是否注册
        boolean b = coreUserInfoClient.checkMobile(mobile);
       if (b){
           return R.error().message("手机号已经被注册");
       } else {
           if(RegexValidateUtils.checkCellphone(mobile)){
               HashMap<String, Object> map = new HashMap<>();
               String code = RandomUtils.getFourBitRandom();

               //将验证码存入redis
               redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code,5, TimeUnit.MINUTES);
               return R.ok().message("短信发送成功");
           }else {
               //手机号码不能为空
               Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
               //手机号码是否合法
               Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

               HashMap<String, Object> map = new HashMap<>();
               String code = RandomUtils.getFourBitRandom();

//        随机生成4位数验证码
               map.put("code", code);

               smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

               //将验证码存入redis
               redisTemplate.opsForValue().set("srb:sms:code:+" + mobile, code,5, TimeUnit.MINUTES);

               return R.ok().message("短信发送成功");
           }
       }

    }
}
